import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import '../../widgets/MyLocalImage.dart';
import '../../widgets/TextView.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';

import '../../api/ApiUtils.dart';
import '../../api/request/LoginRegisterRequest.dart';
import '../../config/AppInfo.dart';
import '../../config/Constant.dart';
import '../../res.dart';
import '../../utils/color/ColorUtils.dart';
import '../../utils/userbloc/user_bloc.dart';
import '../WebViewPage/WebViewPage.dart';
import '../dialog/Dialog.dart';
import '../home/HomeTabBar.dart';
import 'Verification.dart';

// const List<String> scopes = <String>[
//   'email',
//   'https://www.googleapis.com/auth/contacts.readonly',
// ];
//
// GoogleSignIn _googleSignIn = GoogleSignIn(
//   // Optional clientId
//   clientId:
//       '919581430909-kfe24ph82neir43op2ms6kmlpec6vi5r.apps.googleusercontent.com',
//   scopes: scopes,
// );
const List<String> scopes = <String>[
  'email',
  'https://www.googleapis.com/auth/contacts.readonly',
  "https://www.googleapis.com/auth/userinfo.profile"
];

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: scopes,
);

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  GoogleSignInAccount? _currentUser;
  bool _isAuthorized = false; // has granted permissions?

  bool shouldUseFirebaseEmulator = false;

  late final FirebaseApp app;
  late final FirebaseAuth auth;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _googleSignIn.onCurrentUserChanged
        .listen((GoogleSignInAccount? account) async {
      // In mobile, being authenticated means being authorized...
      bool isAuthorized = account != null;
      // However, in the web...
      if (kIsWeb && account != null) {
        isAuthorized = await _googleSignIn.canAccessScopes(scopes);
      }
      GoogleSignInAuthentication googleAuth = await account!.authentication;
      String? accessToken = googleAuth.idToken;
      EasyLoading.show(status: "loading");
      apiShow(
          api: google(accessToken!),
          success: (result) {
            UserBlocTool.saveAuth(result.data[Constant.Authorization]);
            apiShow(
                api: info(),
                success: (r) {
                  // print(UserBlocTool.getUser()!.toJson());
                  EasyLoading.dismiss();
                  Get.off(const HomeTabBar());
                },
                failure: (e) {
                  EasyLoading.dismiss();
                });
          },
          failure: (e) {
            EasyLoading.dismiss();
            if (e.code == 8000) {
              Get.off(Bind(
                url: account.photoUrl!,
                name: account.displayName!,
                email: account.email,
                token: accessToken,
              ));
            }
          });
      setState(() {
        _currentUser = account;
        _isAuthorized = isAuthorized;
      });

      // Now that we know that the user can access the required scopes, the app
      // can call the REST API.
      if (isAuthorized) {
        // unawaited(_handleGetContact(account!));
      }
    });
  }

  Future<void> initializeApp() async {
    // app = await Firebase.initializeApp();
    // auth = FirebaseAuth.instanceFor(app: app);
    //
    // if (shouldUseFirebaseEmulator) {
    //   await auth.useAuthEmulator('localhost', 9099);
    // }
    final LoginResult result = await FacebookAuth.instance
        .login(); // by default we request the email and the public profile
// or FacebookAuth.i.login()
    if (result.status == LoginStatus.success) {
      // you are logged
      final AccessToken accessToken = result.accessToken!;
    } else {
      print(result.status);
      print(result.message);
    }
  }

  Future<void> _handleSignIn() async {
    try {
      await _googleSignIn.signIn();
    } catch (error) {
      print("1111111111111111111$error");
    }
  }

  void dialog() {
    Get.bottomSheet(const MyDialog());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 32),
        color: Colors.white,
        alignment: Alignment.center,
        child: Column(
          // crossAxisAlignment: CrossAxisAlignment.center,
          // verticalDirection: VerticalDirection.down,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: [
            const SizedBox(
              height: 160,
            ),
            MyLocalImage(
              Res.sys_img_logo3x,
              width: 230,
              height: 48,
              onclick: () {
                // Get.to(const GoogleLogin());
                EasyLoading.show(status: 'loading...', dismissOnTap: true);
                //EasyLoading.showToast('Toast');
              },
            ),
            Text(
              "mobile_pdf".tr,
              style: TextStyle(color: rgba(150, 151, 153, 1), fontSize: 14),
            ),
            const SizedBox(
              height: 80,
            ),
            InkWell(
              onTap: () {
                // Get.off(const HomeTabBar());
                _handleSignIn();
              },
              child: Container(
                height: 52,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: rgba(0, 132, 255, 1),
                    borderRadius: BorderRadius.circular(6)),
                child: Stack(
                  fit: StackFit.expand,
                  alignment: Alignment.center,
                  children: [
                    const Positioned(
                      left: 12,
                      child: Image(
                        image: AssetImage(Res.sys_icon_login_google3x),
                        width: 24,
                        height: 24,
                      ),
                    ),
                    Container(
                      alignment: Alignment.center,
                      child: Text(
                        "continue_with_google".tr,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            // InkWell(
            //   onTap: () {
            //     // Get.to(const GoogleLogin());
            //     initializeApp();
            //   },
            //   child: Container(
            //     height: 52,
            //     alignment: Alignment.center,
            //     decoration: BoxDecoration(
            //         color: rgba(247, 247, 247, 1),
            //         borderRadius: BorderRadius.circular(6)),
            //     child: Stack(
            //       fit: StackFit.expand,
            //       alignment: Alignment.center,
            //       children: [
            //         const Positioned(
            //           left: 12,
            //           child: Image(
            //             image: AssetImage(Res.sys_icon_login_facebook3x),
            //             width: 24,
            //             height: 24,
            //           ),
            //         ),
            //         Container(
            //           alignment: Alignment.center,
            //           child: const Text(
            //             "Facebook",
            //           ),
            //         ),
            //       ],
            //     ),
            //   ),
            // ),
            // const SizedBox(height: 16),
            InkWell(
              onTap: () {
                dialog();
              },
              child: Container(
                height: 52,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: rgba(247, 247, 247, 1),
                    borderRadius: BorderRadius.circular(6)),
                child: Stack(
                  fit: StackFit.expand,
                  alignment: Alignment.center,
                  children: [
                    const Positioned(
                      left: 12,
                      child: Image(
                        image: AssetImage(Res.sys_icon_login_email3x),
                        width: 24,
                        height: 24,
                      ),
                    ),
                    Container(
                      alignment: Alignment.center,
                      child: Text(
                        "email".tr,
                        style: TextStyle(color: Colors.black),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const Spacer(),
            TextView(
              "continue_as_guest".tr,
              style: TextStyle(
                  color: rgba(
                    23,
                    70,
                    143,
                    1,
                  ),
                  fontWeight: FontWeight.bold),
              onclick: () {
                Get.to(const HomeTabBar());
              },
            ),
            const SizedBox(height: 24),
            Text(
              "agree".tr,
              style: TextStyle(color: rgba(100, 101, 102, 1)),
            ),
            Text.rich(
              TextSpan(children: [
                TextSpan(
                  text: "terms_service".tr,
                  style: const TextStyle(decoration: TextDecoration.underline),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.to(WebViewPage(
                        PROTOCOL_SUPPORT,
                        title: "terms_service".tr,
                      ));
                    },
                  //
                ),
                TextSpan(
                    text: "   and   ",
                    style: TextStyle(
                      color: rgba(100, 101, 102, 1),
                    )),
                TextSpan(
                  text: "privacy_policy".tr,
                  style: const TextStyle(decoration: TextDecoration.underline),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.to(WebViewPage(
                        "https://www.baidu.com/",
                        title: "privacy_policy".tr,
                      ));
                    },
                ),
              ]),
              style: TextStyle(color: rgba(23, 70, 143, 1)),
            ),
            const SizedBox(height: 24),
          ],
        ),
      ),
    );
  }
}
